package com.mjk.common.core.dcc;


import com.mjk.common.util.ObjectUtils;
import lombok.Getter;
import org.apache.zookeeper.ZooKeeper;

public class DccClient {
	public static final String NODE_PATH_SEPARATOR = "/";
	
	@Getter
    private final DccSessionHolder holder;
	
	private final DccWatcher nodeWatcher;
	
	@Getter
    private final ZooKeeper zk;

    public DccClient(String zkHost, int timeout) {
		zkHost = vaildZkHost(zkHost);
		holder = new DccSessionHolder(zkHost, timeout);
		zk = holder.connect();
		nodeWatcher = new DccWatcher(zk);

		holder.addHoldListener(nodeWatcher::reconnect);
	}
	/**
	 * 获取zk地址
     */
	public String vaildZkHost(String host){
		if(!ObjectUtils.isEmpty(host)){
			if(host.contains("zookeeper://")){
				return host.replace("zookeeper://", "");
			}
			return host;
		}
		return "";
	}
	
	public String rightPath(String path) {
		if (ObjectUtils.isEmpty(path)) {
			return "";
		}
		if (!path.startsWith(NODE_PATH_SEPARATOR)) {
			path = NODE_PATH_SEPARATOR + path;
		}
		return path;
	}

	public void registDataListener(String path, DccWatcher.DataListener listener) {
		path = rightPath(path);
		this.nodeWatcher.addDataListener(path, listener);
	}

	public void registNodeListener(String path, DccWatcher.NodeListener nodeListener) {
		path = rightPath(path);
		this.nodeWatcher.addNodeListener(path, nodeListener);
	}
	
	public void unRegistDataListener(String path) {
		path = rightPath(path);
		this.nodeWatcher.removeDataListener(path);
	}

	public void unRegistNodeListener(String path) {
		path = rightPath(path);
		this.nodeWatcher.removeNodeListener(path);
	}
	
    public String readData(String path) {
        return this.nodeWatcher.readData(path);
    }

    public void writeData(String path, Object data) {
        writeData(path, data, true);
    }
    public void writeData(String path, Object data,boolean isPersistent) {
        path = rightPath(path);       
        this.nodeWatcher.writeData(path, data,isPersistent);
    }

}
